package com.wobuwen.demossm.service.impl;

import com.wobuwen.demossm.mapper.UserMapper;
import com.wobuwen.demossm.model.User;
import com.wobuwen.demossm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public boolean validateLogin(String username, String password) {
        // 根据用户名获取密码
        String storedPassword = userMapper.getPasswordByUsername(username);
        // 验证密码是否匹配
        return storedPassword != null && storedPassword.equals(password);
    }
    
    @Override
    public boolean addUser(User user) {
        // 检查用户名是否已存在
        User existingUser = findByUsername(user.getUsername());
        if (existingUser != null) {
            return false; // 用户名已存在
        }
        
        // 添加用户
        int rows = userMapper.insertUser(user);
        return rows > 0;
    }
    
    @Override
    public boolean updateUser(User user) {
        // 检查用户是否存在
        User existingUser = findByUsername(user.getUsername());
        if (existingUser == null) {
            return false; // 用户不存在
        }
        
        // 更新用户
        int rows = userMapper.updateUser(user);
        return rows > 0;
    }
    
    @Override
    public boolean deleteUser(String username) {
        // 检查用户是否存在
        User existingUser = findByUsername(username);
        if (existingUser == null) {
            return false; // 用户不存在
        }
        
        // 删除用户
        int rows = userMapper.deleteUser(username);
        return rows > 0;
    }
}